package com.example.myapplication2;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class SmsReadActivity extends AppCompatActivity {

    private SmsObserver smsObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms_read);
        //注册通知
        // notifyForDescendants true,全部监听
        // notifyForDescendants false,精确监听
        Uri uri=Uri.parse("content://sms");
        smsObserver = new SmsObserver(this);
        getContentResolver().registerContentObserver(uri,true, smsObserver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁通知
        getContentResolver().unregisterContentObserver(smsObserver);
    }
    //监听回调方法
    private static class SmsObserver extends ContentObserver{
        private final Context context;
        public SmsObserver(Context context) {
            super(new Handler(Looper.getMainLooper()));
            this.context=context;
        }

        @Override
        @SuppressLint("Range")
        public void onChange(boolean selfChange, @Nullable Uri uri) {
            System.out.println(uri.toString());
            super.onChange(selfChange, uri);
            if (uri.toString().equals("content://sms/inbox-insert")){
                Cursor query = context.getContentResolver().query(Uri.parse("content://sms/inbox"), new String[]{"address", "body", "date"}
                        ,null,null,"date DESC");
                if (query==null){
                    return;
                }
                if (query.getCount()>0){
                    if (query.moveToNext()){
                        String address = query.getString(query.getColumnIndex("address"));
                        String body = query.getString(query.getColumnIndex("body"));
                        String date = query.getString(query.getColumnIndex("date"));
                        System.out.println("开始");
                        System.out.println(address);
                        System.out.println(body);
                        System.out.println(date);
                        System.out.println("结束");
                    }
                    query.close();
                }
            }
        }
    }
}